<template>
  <div class="content">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header content="详情" @back="goback"></el-page-header>
        <div class="card-box--setbtn" v-if="isEdit">
          <el-button @click="goback">取消</el-button>

          <el-button type="primary" :loading="saveLoading" @click="handleSubmit"
            >保存</el-button
          >
        </div>
      </div>
    </el-card>
    <el-card class="card-box form-box">
      <el-form
        :disabled="!isEdit"
        :model="formData"
        ref="formRef"
        @submit.prevent
        :rules="formRules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属项目" prop="projectManageId">
              <el-select
                style="width: 100%"
                popper-class="project-box"
                v-model="formData.projectManageId"
                clearable
                placeholder="请选择"
                value-key="id"
                @change="handleSelected"
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectCode">
              <el-input disabled v-model.trim="formData.projectCode"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model.trim="formData.contractName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractNum">
              <el-input v-model.trim="formData.contractNum"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="合同签订时间" prop="ext1">
              <el-date-picker
                v-model="formData.ext1"
                type="date"
                value-format="YYYY-MM-DD"
                clearable
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="甲方单位" prop="ext2">
              <el-cascader
                ref="cascader"
                style="width: 100%"
                popper-class="dept-cas"
                v-model="formData.ext2"
                clearable
                filterable
                :options="deptList"
                :props="defaultProps"
                @change="handleCheckChange"
                placeholder="输入名称搜索"
              />
              <!-- <el-select
                v-model="formData.partyA"
                clearable
                placeholder="请选择"
                style="width: 100%"
                ref="treeSelect"
              >
                <el-option :value="deptList">
                  <el-tree
                    id="tree-option"
                    :data="deptList"
                    accordion
                    node-key="id"
                    ref="partyATreeRef"
                    highlight-current
                    :props="defaultProps"
                    @check-change="handleCheckChange"
                    check-on-click-node
                    :expand-on-click-node="false"
                  ></el-tree>
                </el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="乙方单位" prop="partyB">
              <!-- <el-input v-model.trim="formData.partyB"></el-input> -->
              <el-select
                v-model="formData.partyB"
                style="width: 100%"
                filterable
                clearable
                remote
                placeholder="请输入名称搜索"
                :remote-method="searchCommanyData"
                value-key="id"
              >
                <el-option
                  id="default-option"
                  v-for="item in companyList"
                  :key="item.id"
                  :label="item.companyName"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="合同附件" prop="contractAttachmentArr">
              <el-upload
                name="uploadFile"
                multiple
                :accept="acceptTypes"
                :action="uploadComUrl"
                :headers="uploadHeaders"
                :on-success="handleSuccess"
                :on-remove="handleRemove"
                :on-error="handleError"
                :file-list="defaultFileList"
                :before-upload="beforeAvatarUpload"
                :on-preview="handlePreview"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入内容"
                v-model="formData.remark"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { cloneDeep } from "lodash-es";
import { postDeptList } from "/@/api/dept";
import { postSysCompanyList } from "/@/api/organization";
import { useUpload } from "/@/hooks";
import { useRoute, useRouter } from "vue-router";
import {
  getContractInfo,
  postContractAdd,
  postContractUpdate
} from "/@/api/contract";
import NotifMessage from "/@/utils/message/notification";
import { postProjectList } from "/@/api/project";
const {
  handleError,
  beforeAvatarUpload,
  uploadComUrl,
  acceptTypes,
  uploadHeaders,
  onInitFileList
} = useUpload();
const router = useRouter();
const handlePreview = (item: any) => {
  window.open(
    `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
  );
};
const cascader = ref<HTMLFormElement | null>(null) as any;
const formRef = ref<HTMLFormElement | null>(null) as any;
const route = useRoute();
const defaultProps = {
  children: "children",
  label: "deptDescShrt",
  value: "id",
  checkStrictly: true,
  emitPath: false
};
let projectList = ref([]);
let saveLoading = ref(false);

let formData = reactive({
  projectManageId: "",
  projectCode: "",
  contractName: "",
  contractNum: "",
  ext1:"",
  contractAttachmentArr: [],
  partyA: "",
  ext2:null,
  partyB: null,
  ext3:"",
  remark: "",
  id: ""
});

let deptList = ref([]);
let companyList = ref([]);
const formRules = ref({
  projectManageId: [
    { required: true, message: "请选择所属项目", trigger: "change" }
  ],
  contractName: [
    { required: true, message: "请输入合同名称", trigger: "change" }
  ],
  contractNum: [
    { required: true, message: "请输入合同编号", trigger: "change" }
  ],
  ext1: [
    { required: true, message: "请选择合同签订时间", trigger: "change" }
  ],
  ext2: [{ required: true, message: "请填写甲方单位", trigger: "change" }],
  partyB: [{ required: true, message: "请填写乙方单位", trigger: "change" }],
  contractAttachmentArr: [
    { required: true, message: "请上传附件", trigger: "change" }
  ]
});

/* 上传 -- start */

let defaultFileList = ref([]);

const handleSelected = item => {
  const target = projectList.value.find(el => el.id === item);
  formData.projectCode = target.projectCode;
};

const getProjectList = async () => {
  try {
    const { code, data } = await postProjectList({ pageNum: 1, pageSize: 0 });
    if (code === 200) {
      projectList.value = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};

const goback = () => {
  router.push("/project/contract");
};

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
  formData.contractAttachmentArr = formData.contractAttachmentArr.filter(
    item => {
      const uuid = file.response ? file.response.data.uuidFile : file.uuidFile;
      return item.uuidFile !== uuid;
    }
  );
};

const handleSuccess = (res, file, fileList) => {
  if (res.code === 200) {
    defaultFileList.value = fileList;
    formData.contractAttachmentArr.push(res.data);
  }
  formRef.value.clearValidate();
};

const handleSubmit = async (): Promise<any> => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  const copyFormData = cloneDeep(formData);
  copyFormData.partyB = formData.partyB.companyName;
  copyFormData.ext3 = formData.partyB.id;
  if (route.query.id) {
    copyFormData.id = route.query.id;
    saveLoading.value = true;
    const { code, message } = await postContractUpdate(copyFormData);
    saveLoading.value = false;
    if (code === 200) {
      NotifMessage.success(message);
      goback();
    }
  } else {
    saveLoading.value = true;
    const { code, message } = await postContractAdd(copyFormData);
    saveLoading.value = false;
    if (code === 200) {
      NotifMessage.success(message);
      goback();
    }
  }
};

const initDeptList = async () => {
  const { code, data } = await postDeptList({
    pageSize: 0
  });
  if (code === 200) {
    deptList.value = data;
  }
};

const handleCheckChange = () => {
  const selected = cascader.value.getCheckedNodes();
  if (selected.length > 0) {
    const data = selected[0].data;
    formData.partyA = data.deptDescShrt;
    formData.ext2 = data.id;
  }
};

const searchCommanyData = (query = "") => {
  if (!query) {
    companyList.value = [];
    return;
  }
  getCommanyData(query);
};

async function getCommanyData(query = "") {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await postSysCompanyList(params);
    if (code === 200) {
      companyList.value = data.list.map(item => {
        return { id: item.id, companyName: item.companyName };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

getProjectList();
initDeptList();
getCommanyData();

const getContractDetail = async () => {
  if (route.query.id) {
    const { data } = await getContractInfo({ id: route.query.id });
    formData.projectManageId = data.projectManageId;
    formData.contractName = data.contractName;
    formData.contractNum = data.contractNum;
    formData.contractAttachmentArr = data.contractAttachmentArr;
    formData.partyA = data.partyA;
    formData.ext2 = data.ext2;
    formData.partyB = {
      companyName: data.partyB,
      id: +data.ext3
    };
    formData.ext1 = data.ext1;
    formData.remark = data.remark;
    formData.projectCode = route.query.code as any;
    defaultFileList.value = onInitFileList(data.contractAttachmentArr);
  }
};
onMounted(async () => {
  getContractDetail();
});
const isEdit = route.query.mode === "edit" ? true : false;
</script>

<style lang="scss" scoped>
.el-select-dropdown__item {
  height: auto;
  // min-height: 100px;
  // max-height: 274px;
  padding: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}
.el-select-dropdown_item.selected {
  font-weight: normal;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

// #tree-option
#tree-option :deep .el-tree-node__content {
  height: auto;
  padding: 0 10px;
}
// #tree-option :deep .el-select-dropdown__list {
//   padding: 0 6px;
// }
#tree-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  margin-right: 10px;
}

.el-tree :deep .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}
.el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
#default-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  // margin-right: 10px;
}

#default-option {
  padding: 0 10px;
}
.content {
  :deep .el-page-header__content {
    font-size: 16px;
  }
  .card-box {
    margin-bottom: 10px;
    &--headerwrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    &--setbtn {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 140px;
    }
  }

  .header__wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.form-box {
  margin-top: 10px;
}
.form-info {
  margin-bottom: 20px;
}
.header-btns {
  text-align: right;
}
</style>
